﻿using DeviceCommons.DataHandling;
using DeviceCommons.DeviceMessages.Abstractions;
using DeviceCommons.DeviceMessages.Models;
using System.Buffers;

namespace DeviceCommons.DeviceMessages.Serialization.V1.Serializers
{
    public class DeviceMessageHeaderSerializer : AbstractMessageSerializer<IDeviceMessageHeader>, IDeviceMessageHeaderSerializer
    {
        public DeviceMessageHeaderSerializer() : base(new DeviceMessageHeader())
        {
        }

        private readonly static int HEADERLENGTH = 4;
        public override void Serializer(ArrayBufferWriter<byte> writer, IDeviceMessageHeader model)
        {
            int existingLength = writer.WrittenCount;

            using var pool = DeviceMessageArrayPool.MemoryPool.Rent(existingLength + HEADERLENGTH);

            writer.WrittenMemory.ToArray().CopyTo(pool.Memory);
            ReadOnlySpan<byte> existingData = pool.Memory.Span[..existingLength];

            writer.Clear();

            writer.Write(model.Header);
            writer.Write([model.Version]);
            writer.Write([model.Mark]);

            if (existingLength > 0) writer.Write(existingData);
        }
    }
}
